package com.itlong.cloud.controller.system;

import com.itlong.cloud.POJO.DTO.property.PropertyAddBankCardDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyBankManageGetPageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateAddressVO;
import com.itlong.cloud.POJO.VO.property.PropertyBankManageGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.operate.IOperateAddressManageServiceClient;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.paymenthub.IPropertyBankCardManageServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业银行卡管理控制器
 * </desc>
 *
 * @createDate 2018/09/20
 */
@RestController
@RequestMapping("/system/bankCard")
@RefreshScope
public class PropertyBankCardManageController {
    private static final Logger LOG = LoggerFactory.getLogger(PropertyBankCardManageController.class);

    @Autowired
    RedisService redisService;

    @Autowired
    IPropertyBankCardManageServiceClient iPropertyBankCardManageServiceClient;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    IOperateAddressManageServiceClient iOperateAddressManageServiceClient;
    /**
     * <desc>
     *      添加时获取物业银行手机号及支付密码信息
     * </desc>
     *
     * @param projectId
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/getBankPayConf")
    @ResponseBody
    public Object getBankPayConf(String projectId){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyBankCardManageServiceClient.getBankPayConf(projectId));
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_银行卡管理banOrUse】添加时获取物业银行手机号及支付密码信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      验证银行账户唯一性
     * </desc>
     *
     * @param bankCardNo
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/checkBankCardOnly")
    @ResponseBody
    public Object checkBankCardOnly(String bankCardNo,String bankCardId){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankCardNo = request.getAttribute("bankCardNo") == null ? null : request.getAttribute("bankCardNo").toString();
            bankCardId = request.getAttribute("bankCardId") == null ? "" : request.getAttribute("bankCardId").toString();
            int result = iPropertyBankCardManageServiceClient.checkBankCardOnly(bankCardNo,bankCardId);
            if(result > 0){
                messageVO = new MessageVO(PropertyErrorCodeEnum.BANK_CARD_EXISTS.getErrorCode());
            }else{
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_银行卡管理checkBankCardOnly】验证银行账户唯一性失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      发送验证码
     * </desc>
     *
     * @param phoneNum
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/addBankSendMessage")
    @ResponseBody
    public Object addBankSendMessage(String projectId,String phoneNum){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            phoneNum = request.getAttribute("phoneNum") == null ? null : request.getAttribute("phoneNum").toString();
            //查询项目下是否已有手机号
            String bankPhone = iPropertyBankCardManageServiceClient.getProjectBankPhone(projectId);
            if (StringUtils.isNotBlank(bankPhone)) {
                phoneNum = bankPhone;
            }
            String smsCode = NumberHandlerUtil.randomNum(6);
            while (smsCode.substring(0,1).equals("0")){
                smsCode = NumberHandlerUtil.randomNum(6);
            }
            String content = "验证码:" + smsCode + ",该验证码将在30分钟后失效.";
            Map<String, Object> map = (HashMap) redisService.getObject(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_COUNT + phoneNum, HashMap.class);
            if (map == null) {
                map = new HashMap<>();
            }
            Integer count = (Integer) map.get("count");
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            if (count > 3) {
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_COUNT_SURPASS.getErrorCode());
            } else {
                map.put("count", count);
                map.put("smsCode", smsCode);
                iIotTpSmsServiceClient.sendSmsCodeByPhone(phoneNum, content);
                redisService.set(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_COUNT + phoneNum, RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_COUNT_TIME, map);
                //保存验证码
                boolean check = redisService.set(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + phoneNum,RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_CACHE_TIME,smsCode);
                //LOG.info(String.format("【物业银行卡发送短信：手机号%s,%s】",phoneNum,check));
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理addBankSendMessage】发送验证码失败", e);
        }
    }

    /**
     * <desc>
     *      删除银行卡
     * </desc>
     *
     * @param bankCardId
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/deleteBankCard")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.DELETE_BANK_CARD_LOG_DESC)
    public Object deleteBankCard(String bankCardId) throws IOException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankCardId = request.getAttribute("bankCardId") == null ? null : request.getAttribute("bankCardId").toString();
            Integer result = iPropertyBankCardManageServiceClient.deleteBankCard(bankCardId);
            if(result > 0){
                return new MessageVO(bankCardId,BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }else{
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理deleteBankCard】删除银行卡失败", e);
        }
    }

    /**
     * <desc>
     *      下载申请表
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/09/20
     * @return
     */
    @RequestMapping(path = "/downloadForm", method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object downloadForm() {
        MessageVO messageVO;
        try {
            String templateFilePath = FILE_ACCESS_URL + FileCatalogEnum.PROJECT_STATIC_FILE.getType()
                    + PlatformConstants.BANK_CARD_NAMAGE_FORM;
            URI excelTemplateDownLoadUrl = new URI(templateFilePath);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) excelTemplateDownLoadUrl.toString());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理downloadForm】下载申请表失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取账号详情
     * </desc>
     *
     * @param bankCardId
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/getBankCardInfo")
    @ResponseBody
    public Object getBankCardInfo(String bankCardId) throws IOException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankCardId = request.getAttribute("bankCardId") == null ? null : request.getAttribute("bankCardId").toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyBankCardManageServiceClient.getBankCardInfo(bankCardId));
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理getBankCardInfo】获取账号详情失败",e);
        }
    }

    /**
     * <desc>
     *      添加银行卡
     * </desc>
     *
     * @param dto
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/addBankCard")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ADD_BANK_CARD_LOG_DESC)
    public Object addBankCard(PropertyAddBankCardDTO dto) throws IOException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(PropertyAddBankCardDTO.class, request);
            //验证验证码是否正确
            //查询项目下手机号
            String bankPhone = iPropertyBankCardManageServiceClient.getProjectBankPhone(dto.getProjectId());
            //获取缓存中的验证码
            String smsCode;
            if(StringUtils.isBlank(bankPhone)){
                smsCode = (String) redisService.getObject(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + dto.getPhoneNum(), String.class);
                bankPhone = dto.getPhoneNum();
            }else{
                smsCode = (String) redisService.getObject(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + bankPhone, String.class);
            }
            if(StringUtils.isBlank(smsCode)){
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_EXISTS.getErrorCode());
            }
            if(!smsCode.equals(dto.getValidCode())){
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_ERROR.getErrorCode());
            }else{
                redisService.del(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + bankPhone);
            }
            return new MessageVO(iPropertyBankCardManageServiceClient.addBankCard(dto), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理addBankCard】添加银行卡失败",e);
        }
    }

    /**
     * <desc>
     *      修改银行卡
     * </desc>
     *
     * @param dto
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/updateBankCard")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_BANK_CARD_LOG_DESC)
    public Object updateBankCard(PropertyAddBankCardDTO dto) throws IOException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(PropertyAddBankCardDTO.class, request);
            //验证验证码是否正确
            //查询项目下手机号
            String bankPhone = iPropertyBankCardManageServiceClient.getProjectBankPhone(dto.getProjectId());
            //获取缓存中的验证码
            String smsCode = (String) redisService.getObject(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + bankPhone, String.class);
            if(StringUtils.isBlank(smsCode)){
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_EXISTS.getErrorCode());
            }
            if(!smsCode.equals(dto.getValidCode())){
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_ERROR.getErrorCode());
            }else{
                redisService.del(RedisConstant.BANK_CARD_PHONE_SEND_MESSAGE_KEY + bankPhone);
            }
            return new MessageVO(iPropertyBankCardManageServiceClient.addBankCard(dto), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理updateBankCard】修改银行卡失败",e);
        }
    }

    /**
     * <desc>
     *      用户分页列表
     * </desc>
     *
     * @param pageDTO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @RequestMapping(path = "getPage",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getUserPage(PropertyBankManageGetPageDTO pageDTO){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyBankManageGetPageDTO.class, request);
            Page<PropertyBankManageGetPageVO> page=iPropertyBankCardManageServiceClient.getPage(pageDTO);
            page.getRows().forEach(vo->{
                vo.setBankCardNo("****"+vo.getBankCardNo().substring(vo.getBankCardNo().length()-4,vo.getBankCardNo().length()));
            });
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_用户getPage】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取地址信息列表
     * <desc/>
     *
     * @param
     * @return
     * @author Jiaqi.X
     * @createDate  2018/09/26
     */
    @RequestMapping(path = "/getAddress" , method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object getAddress(String parentAddressId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            parentAddressId = request.getAttribute("parentAddressId") == null ? null : request.getAttribute("parentAddressId").toString();
            if (StringUtils.isBlank(parentAddressId)){
                parentAddressId = "0";
            }
            List<OperateAddressVO> addrs = iOperateAddressManageServiceClient.getAddress(parentAddressId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), addrs);
        }catch (Exception e){
            throw new DataAccessException("【物业-银行卡管理】获取地址信息列表失败",e);
        }
    }

    /**
     * <desc>
     *      获取银行信息
     * <desc/>
     *
     * @param
     * @return
     * @author Jiaqi.X
     * @createDate  2018/09/26
     */
    @RequestMapping(path = "/getBanks" , method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object getBanks(String bankName){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            bankName = request.getAttribute("bankName") == null ? null : request.getAttribute("bankName").toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyBankCardManageServiceClient.getBanks(bankName));
        }catch (Exception e){
            throw new DataAccessException("【物业-银行卡管理getBanks】获取银行信息列表失败",e);
        }
    }


    /**
     * <desc>
     *      获取物业银行卡列表信息
     * <desc/>
     *
     * @param
     * @return
     * @author Jiaqi.X
     * @createDate  2018/09/26
     */
    @RequestMapping(path = "/getBankCards" , method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object getBankCards(String projectId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyBankCardManageServiceClient.getBankCards(projectId));
        }catch (Exception e){
            throw new DataAccessException("【物业-银行卡管理getBankCards】获取物业银行卡列表信息失败",e);
        }
    }
}
